"""
广播机制

右对齐：从右往左看，只要对应维度。要么相等，要么有一个是1就满足广播条件
a.shape = (2,1,1,3)
b.shape=(4,2,3)
(a+b).shape=(2*4*2*3)
"""

import torch

def test1():
    a = torch.randn(2,3)
    b = torch.randn(3)
    c = a + b

    # a: 2*3
    # b: 3  -->  1*3
    # c: 2*3

    print(a)
    print(b)
    print(c)
    print(c.shape)


def test2():
    print(f"广播机制")
    a = torch.rand(2, 1, 1)
    b = torch.rand(3)
    # a: 2*1*1
    # b: 3  -->  1*1*3
    # ==>  a+b的维度应该是2*1*3
    print("==== a ====")
    print(a)
    print(a.shape)

    print("==== b ====")
    print(b)
    print(b.shape)

    print("==== a + b ====")
    c = a + b
    print(c)
    print(c.shape)


if __name__ == '__main__':
    test1()
    test2()
